package com.tengju.bff.interfaces.covercharge.util;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 操作 Html工具类
 *
 * @author wzy
 */
@Slf4j
public class HtmlUtils {
    /**
     * The constant log.
     */
    private static final String CONTENT_TYPE = "Content-type";

    private HtmlUtils() {
    }

    /**
     * <br>
     * <b>功能：</b>输出json格式<br>
     * <b>作者：</b>罗泽军<br>
     * <b>日期：</b> Dec 14, 2011 <br>
     *
     * @param response the response
     * @param jsonStr  the json str
     * @throws Exception
     */
    public static void writerJson(HttpServletResponse response, String jsonStr) {
        response.setHeader(CONTENT_TYPE, "application/json;charset=UTF-8");
        writer(response, jsonStr);
    }

    /**
     * Writer json.
     *
     * @param response the response
     * @param object   the object
     */
    public static void writerJson(HttpServletResponse response, Object object) {
        writerJson(response, JSONUtil.toJsonStr(object));
    }

    /**
     * <br>
     * <b>功能：</b>输出HTML代码<br>
     * <b>作者：</b>罗泽军<br>
     * <b>日期：</b> Dec 14, 2011 <br>
     *
     * @param response the response
     * @param htmlStr  the html str
     * @throws Exception
     */
    public static void writerHtml(HttpServletResponse response, String htmlStr) {
        response.setHeader(CONTENT_TYPE, "text/html;charset=UTF-8");
        //解决宝付认证支付360浏览器不兼容问题，输出方式换种写法
        response.setContentType("text/html; charset=UTF-8");
        writer(response, htmlStr);
    }

    /**
     * Writer xml.
     *
     * @param response the response
     * @param htmlStr  the html str
     */
    public static void writerXml(HttpServletResponse response, String htmlStr) {
        response.setHeader(CONTENT_TYPE, "text/xml;charset=UTF-8");
        writer(response, htmlStr);
    }

    /**
     * Writer html.
     *
     * @param response the response
     * @param object   the object
     */
    public static void writerHtml(HttpServletResponse response, Object object) {
        writerHtml(response, JSONUtil.toJsonStr(object));
    }

    /**
     * shuchu
     *
     * @param response the response
     * @param htmlStr  the htmlStr
     */
    public static void writer(HttpServletResponse response, String htmlStr) {
        try {
            //设置页面不缓存
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
//            out.print(htmlStr);
            out.print(htmlStr);
            out.flush();
            out.close();
        } catch (Exception e) {
            log.error("writer faild： {}", e);
        }
    }
}
